<template>
  <el-dialog :append-to-body="true" :visible.sync="dialog" :title="isAdd ? '新增评论' : '编辑评论'" width="500px">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
      <el-form-item label="选择宝贝" prop="commodity_id">
        <el-select v-model="form.commodity_id" filterable clearable placeholder="请选择" style="width: 370px;">
          <el-option
            v-for="item in commodityList"
            :key="item.commodity_id"
            :label="item.name"
            :value="item.commodity_id" />
        </el-select>
      </el-form-item>
      <el-form-item label="评价等级" prop="level">
        <el-select v-model="form.level" filterable clearable placeholder="请选择" style="width: 370px;">
          <el-option
            v-for="item in gradeList"
            :key="item.key"
            :label="item.value"
            :value="item.key" />
        </el-select>
      </el-form-item>
      <el-form-item label="评价人" prop="nick">
        <el-input v-model="form.nick" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="用户头像" prop="icon_url">
        <el-upload
          :show-file-list="false"
          :data="{'company_id': companyId }"
          :on-success="userImgSuccess"
          :before-upload="beforeUserImgUpload"
          :action="userHeadUploadApi"
          class="avatar-uploader">
          <img v-if="form.icon_url" :src="form.icon_url" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="评价内容" prop="content">
        <el-input :rows="3" v-model="form.content" type="textarea" style="width: 370px;" placeholder="请输入内容" />
      </el-form-item>
      <el-form-item >
        <el-upload
          ref="upload"
          :data="{'company_id': companyId }"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :before-upload="beforeUserImgUpload"
          :action="albumUploadApi"
          list-type="picture-card">
          <i class="el-icon-plus" />
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img :src="dialogImageUrl" width="100%" alt="">
        </el-dialog>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { addComment } from '@/api/mall/comment'
import Cookies from 'js-cookie'
export default {
  components: { },
  props: {
    isAdd: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      companyId: Cookies.get('company_id'),
      loading: false, dialog: false,
      gradeList: [
        { 'key': 1, 'value': '1星' },
        { 'key': 2, 'value': '2星' },
        { 'key': 3, 'value': '3星' },
        { 'key': 4, 'value': '4星' },
        { 'key': 5, 'value': '5星' }
      ],
      form: {
        commodity_id: '',
        level: 1,
        nick: '',
        icon_url: '',
        content: '',
        urls: []
      },
      rules: {
        commodity_id: [
          { required: true, message: '请选择商品', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '请选择等级', trigger: 'blur' }
        ],
        nick: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入评论内容', trigger: 'blur' }
        ]
      },
      dialogImageUrl: '',
      dialogVisible: false,
      imageUrl: '',
      commodityList: []
    }
  },
  computed: {
    ...mapGetters([
      'userHeadUploadApi',
      'albumUploadApi'
    ])
  },
  methods: {
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      // 表单验证
      this.$refs['form'].validate((valid) => {
        // 通过
        if (valid) {
          this.doAdd()
        }
      })
    },
    doAdd() {
      this.loading = true
      addComment(this.form).then(() => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.init()
      }).catch(() => {
        this.loading = false
      })
    },
    resetForm() {
      this.dialog = false
      this.form = {
        commodity_id: '',
        level: 1,
        nick: '',
        icon_url: '',
        content: '',
        urls: []
      }
      // 上传的内容清空
      this.$refs.upload.clearFiles()
      // 表单清空
      this.$refs['form'].resetFields()
    },
    handleRemove(file, fileList) {
      // 删除图片事件,由于会出现上传相同的图片，oss地址相同，删除一个
      this.form.urls = []
      fileList.forEach(item => {
        this.form.urls.push(item.response)
      })
    },
    handleSuccess(res) {
      this.form.urls.push(res)
    },
    handlePictureCardPreview(file) {
      // 放大预览图片
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    userImgSuccess(res, file) {
      // 用于回显图片内容，不用oss返回的地址主要是节省流量
      this.imageUrl = URL.createObjectURL(file.raw)
      // 后台返回的oss地址，存储对象里，用于保存信息时使用
      this.form.icon_url = res
    },
    beforeUserImgUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
  }
  .avatar {
    width: 80px;
    height: 80px;
    border-radius: 6px;
    display: block;
  }
</style>
